#include "tcpclient.h"
#include "settings/serversetting.h"

TcpClient *TcpClient::mClient = NULL;
const TcpClient::CmdHandler TcpClient::cmdTable[]=
{
//    {"picture",&TcpClient::getPicInfo},
    {"RCD",&TcpClient::updateRecord},
    {"TIME",&TcpClient::syncTime},
//    {"product",&TcpClient::updateProduct},
//    {"id",&TcpClient::updateId},
//    {"user",&TcpClient::updateUser},
//    {"update",&TcpClient::getFileInfo},
    {0,0}
};
TcpClient::TcpClient(QObject *parent) : QObject(parent),mTimeoutCnt(0)
{
    mConnectTimer = new QTimer(this);
    connect(mConnectTimer,SIGNAL(timeout()),this,SLOT(onConnectTimeout()));
    mTickTimer = new QTimer(this);
    connect(mTickTimer,SIGNAL(timeout()),this,SLOT(writeTick()));
    mSocket = new QTcpSocket(this);
    connect(mSocket,SIGNAL(connected()),this,SLOT(onConnected()));
    connect(mSocket,SIGNAL(disconnected()),this,SLOT(onDisconnected()));
    mConnectTimer->start(2000);
    connect(mSocket,SIGNAL(readyRead()),this,SLOT(read()));
    //mIsConnected =false;
}

//bool TcpClient::getPicInfo(QByteArray &data)
//{
//    QString picInfo = QString(data);
//    //fileName = "temp"+picInfo.section("#",0,0);
//    fileSize = picInfo.section("#",1,1).toInt();qDebug()<<fileSize;
//    mNewFile = new QFile(QString("/usr/b"));
//    if(mNewFile->open(QIODevice::WriteOnly))
//    {
//        qDebug()<<"ok";
//        return true;
//    }
//    else {
//        qDebug()<<"error";
//        return false;
//    }
//}
void TcpClient::writeCmd(const QByteArray &cmd, const QString &name)
{
    if(!isConnected())
        return;
    if(name.length()>0){
        QByteArray data = cmd +"," + name.toUtf8()+"\r\n";
        mSocket->write(data);
    }else{
        QByteArray data = cmd +"\r\n";
        mSocket->write(data);
    }
}

void TcpClient::connectToHost()
{
    QTcpSocket::SocketState state = mSocket->state();
    if(state!=QTcpSocket::ConnectedState&&state!=QTcpSocket::ConnectingState)
    {
       QString ip;int port;
       ServerSetting::ServerInfo(&ip,&port);
       mSocket->connectToHost(ip,port);
    }
}

void TcpClient::disConnectFromHost()
{
    mSocket->disconnectFromHost();
}

TcpClient* TcpClient::getInstanse()
{
    if(mClient==NULL)
    {
        mClient = new TcpClient();
    }
    return mClient;
}

TcpClient::~TcpClient()
{
    mSocket->disconnectFromHost();
    delete mSocket;
    delete mConnectTimer;
}

void TcpClient::onConnectTimeout()
{
    QTcpSocket::SocketState state = mSocket->state();
    if(state!=QTcpSocket::ConnectedState&&state!=QTcpSocket::ConnectingState)
    {
       connectToHost();
    }
}

void TcpClient::writeTick()
{
//    mTimeoutCnt++;
//    if(mTimeoutCnt>=3)
//    {
//        mTimeoutCnt = 0;
//        qDebug()<<"timeout"<<"disconnect";
//        disConnectFromHost();
//    }
    writeCmd("Tick","");
}

void TcpClient::onConnected()
{
    mConnectTimer->stop();
    mTickTimer->start(2000);
    qDebug()<<"oncon";
}

void TcpClient::onDisconnected()
{
    mConnectTimer->start();
    mTickTimer->stop();
    //mIsConnected = false;
    emit disconnected();

}

void TcpClient::read()
{
    while(mSocket->canReadLine())
    {
        QByteArray cmd = mSocket->readLine();
        cmd.chop(2);
        //dataCount++;
        QByteArray data =cmd;
        handleReciveData(data);
    }
//    mTimeoutCnt = 0;
//    QByteArray data = mSocket->readAll();
//    if(data.startsWith("size"))
//    {
//        QList<QByteArray> list = data.split('#');qDebug()<<list.at(0)
//                                                         <<list.at(1);
//        picSize = list.at(1).toInt();qDebug()<<"picsize"<<picSize;
//        data=data.mid(data.indexOf("#",5)+1);qDebug()<<data.size();
//    }
//    arr.append(data);
//    qDebug()<<arr.size()<<picSize;
//    if(arr.size()==picSize)
//    {
//        emit picData(arr);
//    }
//    if(arr.size()>160000) disConnectFromHost();

}

//void TcpClient::readFile()
//{
//    qDebug()<<"readfile";
//    QByteArray buf = mSocket->readAll();
//    qint64 len = mNewFile->write(buf);
//    qDebug()<<len;
//    recevSize += len;
//    qDebug()<<recevSize;
//    if(recevSize==fileSize)
//    {qDebug()<<"savefile";
//        QFile oldPic("/usr/a.png");
//        //oldPic.remove();
//        //system("mv /usr/b.png /usr/a.png");
//        emit getApic();
//    }
//}

bool TcpClient::handleReciveData(QByteArray &data)
{
    const CmdHandler *handler = &cmdTable[0];
    while(handler->cmd!=NULL)
    {
        if(data.startsWith(handler->cmd)){
            data.remove(0,strlen(handler->cmd)+1);

            if(handler->handle!=NULL){
                return (this->*(handler->handle))(data);
            }else{
                return false;
            }
        }
        handler++;
    }

    return false;
}

bool TcpClient::updateRecord(QByteArray &array)
{

}

bool TcpClient::syncTime(QByteArray &array)
{
    QByteArray dateStr = " date -s \"" +array + "\"";
    qDebug()<<dateStr;
    DoSystem(dateStr.data());
    DoSystem("hwclock -w");
    return true;
}
